package com.tenglong.teacher.ui.homework;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.homework.HomeWorkStateItem;
import com.tenglong.teacher.ui.utils.MyUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class HomeworkStateAdatper extends BaseAdapter {
    private LayoutInflater inflater;
    private Context cxt;
    private List<HomeWorkStateItem> mData;
    private LruCache<String, BitmapDrawable> mImageCache;
    private ListView listview;

    public HomeworkStateAdatper(Context context, List<HomeWorkStateItem> Data) {
        inflater = LayoutInflater.from(context);
        this.mData = Data;
        this.cxt = context;

        int maxCache = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxCache / 8;
        mImageCache = new LruCache<String, BitmapDrawable>(cacheSize) {
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }
        };
    }

    // 要绑定的条目的数目
    @Override
    public int getCount() {
        return mData.size();
    }

    // 根据一个索引（位置）获得该位置的对象
    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    // 获取条目的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 获取该条目要显示的界面
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (listview == null) {
            listview = (ListView) parent;
        }
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_task, parent, false);

            holder = new ViewHolder();
            holder.iv_studentAvatar = convertView.findViewById(R.id.iv_header);
            holder.tv_createDate = convertView.findViewById(R.id.tv_year_month);
            holder.tv_studentName = convertView.findViewById(R.id.tv_stu_name);
            holder.tv_className = convertView.findViewById(R.id.tv_class_name);
            holder.tv_createTime = convertView.findViewById(R.id.tv_task_time);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        HomeWorkStateItem bean = mData.get(position);

        //加载头像
        if(bean.getStudentAvatar() == null || MyUtils.isUrl(bean.getStudentAvatar()) == false){
            holder.iv_studentAvatar.setImageResource(R.drawable.setting_image_defauft_header);
        }else{
            if (mImageCache.get(bean.getStudentAvatar()) != null) {
                holder.iv_studentAvatar.setImageDrawable(mImageCache.get(bean.getStudentAvatar()));
            } else {
                ImageTask it = new ImageTask();
                it.execute(bean.getStudentAvatar());
            }
        }

        holder.tv_createDate.setText(MyUtils.getDateTimeByFormat(bean.getCreateDate(),"yyyy-MM-dd"));
        holder.tv_createTime.setText(MyUtils.getDateTimeByFormat(bean.getCreateDate(),"HH:mm:ss"));
        holder.tv_studentName.setText(bean.getStudentName());
        holder.tv_className.setText(bean.getClassName());

        int statusID = R.drawable.weipigai;
        switch (bean.getStatus()){
            case MyUtils.HW_STATUS_SUBMIT:
                statusID = R.drawable.weipigai;
                break;
            case MyUtils.HW_STATUS_CORRECT:
                statusID = R.drawable.yipigai;
                break;

        }
        holder.iv_status.setImageResource(statusID);


        return convertView;
    }

    // 新建holder类，对listview进行简单优化
    private class ViewHolder {
/*
*     private String homeworkid; // 作业ID
    private String classId; // 班级ID
    private String studentName;// 学生名字
    private String className;//  班级名称
    private String sessonId;// 作业对话sessionID
    private Date createDate;//发布作业日期
    private String studentAvatar;//学生头像
    private int status;//作业状态
*
* */
        TextView tv_studentName;
        ImageView iv_studentAvatar;
        TextView tv_className;
        TextView tv_createDate;
        TextView tv_createTime;
        ImageView iv_status;
    }

    class ImageTask extends AsyncTask<String, Void, BitmapDrawable> {

        private String imageUrl;

        @Override
        protected BitmapDrawable doInBackground(String... params) {
            imageUrl = params[0];
            Bitmap bitmap = downloadImage();
            BitmapDrawable db = new BitmapDrawable(listview.getResources(),
                    bitmap);
            // 如果本地还没缓存该图片，就缓存
            if (mImageCache.get(imageUrl) == null) {
                mImageCache.put(imageUrl, db);
            }
            return db;
        }

        @Override
        protected void onPostExecute(BitmapDrawable result) {
            // 通过Tag找到我们需要的ImageView，如果该ImageView所在的item已被移出页面，就会直接返回null
            ImageView iv = listview.findViewWithTag(imageUrl);
            if (iv != null && result != null) {
                iv.setImageDrawable(result);
            }
        }

        /**
         * 根据url从网络上下载图片
         *
         * @return
         */
        private Bitmap downloadImage() {
            HttpURLConnection con = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }

            return bitmap;
        }

    }
}
